const PROJECT_KEY = 'music-score-projects';

export const StorageService = {
  // 获取所有项目
  getProjects() {
    const projects = localStorage.getItem(PROJECT_KEY);
    return projects ? JSON.parse(projects) : [];
  },
  
  // 保存项目
  // 增强保存逻辑
  saveProject(projectData) {
    const projects = this.getProjects();
    const existingIndex = projects.findIndex(p => p.id === projectData.id);

    const fullProject = {
      ...projectData,
      createdAt: projectData.createdAt || new Date().toISOString(),
      updatedAt: new Date().toISOString()
    };

    if (existingIndex !== -1) {
      projects[existingIndex] = fullProject;
    } else {
      projects.push({...fullProject, id: Date.now().toString()});
    }

    localStorage.setItem(PROJECT_KEY, JSON.stringify(projects));
    return fullProject;
  },

  // 新增文件导出
  exportProject(projectId, format = 'json') {
    const project = this.getProject(projectId);
    if (!project) throw new Error('项目不存在');

    let content, mimeType, extension;
    switch(format) {
      case 'xml':
        content = this._convertToXML(project);
        mimeType = 'application/xml';
        extension = 'xml';
        break;
      case 'text':
        content = this._convertToText(project);
        mimeType = 'text/plain';
        extension = 'txt';
        break;
      default:
        content = JSON.stringify(project, null, 2);
        mimeType = 'application/json';
        extension = 'json';
    }

    this._downloadFile(content, mimeType, `${project.name}.${extension}`);
  },

  // 新增文件导入
  importProject(file) {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      
      reader.onload = (e) => {
        try {
          const content = e.target.result;
          let project;
          
          if (file.type === 'application/json') {
            project = JSON.parse(content);
          } else if (file.type === 'application/xml') {
            project = this._parseXML(content);
          } else {
            project = this._parseText(content);
          }

          resolve(this.saveProject(project));
        } catch (error) {
          reject(new Error('文件解析失败'));
        }
      };

      reader.readAsText(file);
    });
  },

  // 私有方法
  _downloadFile(content, mimeType, filename) {
    const blob = new Blob([content], { type: mimeType });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = filename;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  },

  _convertToXML(project) {
    return `<?xml version="1.0" encoding="UTF-8"?>
<project>
  <name>${project.name}</name>
  <metadata>
    <title>${project.data.metadata.title}</title>
    <composer>${project.data.metadata.composer}</composer>
    <!-- 其他元数据 -->
  </metadata>
  <!-- 乐谱数据 -->
</project>`;
  },

  _parseXML(content) {
    const parser = new DOMParser();
    const xmlDoc = parser.parseFromString(content, 'text/xml');
    // 实现详细解析逻辑
    return {
      name: xmlDoc.querySelector('name')?.textContent || '未命名项目',
      data: {
        // 解析后的数据
      }
    };
  },
  
  // 删除项目
  deleteProject(id) {
    let projects = this.getProjects();
    projects = projects.filter(p => p.id !== id);
    localStorage.setItem(PROJECT_KEY, JSON.stringify(projects));
  },
  
  // 获取单个项目
  getProject(id) {
    const projects = this.getProjects();
    return projects.find(p => p.id === id);
  }
};